# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request, send_from_directory
from flask_cors import CORS
import json
import os
import subprocess
from datetime import datetime

# 导入路径工具
from path_utils import get_base_dir, get_config_path, get_game_path, get_asset_path, normalize_path, get_python_command

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 游戏配置文件 - 使用路径工具获取正确路径
CONFIG_FILE = get_config_path("games_config.json")

# 默认游戏数据
DEFAULT_GAMES = [
    {
        "id": "tetris",
        "name": "俄罗斯方块",
        "description": "经典的俄罗斯方块游戏，支持多种难度和主题",
        "path": "./game/俄罗斯方块/tetris_game.py",
        "category": "益智",
        "rating": 4.8,
        "play_count": 0,
        "last_played": None,
        "image": "assets/game_log/俄罗斯方块/logo.png",
        "settings": {
            "difficulty": "normal",
            "theme": "classic",
            "sound": True,
            "ghost_piece": True,
            "auto_save": True
        },
        "status": "available"
    },
    {
        "id": "snake",
        "name": "贪吃蛇_不会死亡",
        "description": "经典贪吃蛇游戏，永远不会死亡，挑战你的反应速度",
        "path": "./game/贪吃蛇_不会死亡/tanchishe.py",
        "category": "动作",
        "rating": 4.5,
        "play_count": 0,
        "last_played": None,
        "image": "assets/game_log/贪吃蛇/logo.png",
        "settings": {
            "speed": "medium",
            "board_size": "medium",
            "obstacles": False,
            "sound": True
        },
        "status": "available"
    },
    {
        "id": "tank_battle",
        "name": "坦克大战",
        "description": "经典坦克对战游戏，体验激烈的战斗",
        "path": "./game/坦克大战/tankedazhan.py",
        "category": "动作",
        "rating": 4.6,
        "play_count": 0,
        "last_played": None,
        "image": "assets/game_log/坦克大战/logo.png",
        "settings": {
            "difficulty": "normal",
            "sound": True,
            "player_count": 1
        },
        "status": "available"
    },
    {
        "id": "push_box",
        "name": "推箱子",
        "description": "经典推箱子益智游戏，包含多个关卡，锻炼逻辑思维",
        "path": "./game/推箱子/tuixiangzi.py",
        "category": "益智",
        "rating": 4.2,
        "play_count": 0,
        "last_played": None,
        "image": "assets/game_log/推箱子/logo.png",
        "settings": {
            "level": 1,
            "timer": True,
            "sound": True
        },
        "status": "available"
    },
    {
        "id": "star_collector",
        "name": "星际收集者",
        "description": "太空主题的收集类冒险游戏，探索宇宙收集星星",
        "path": "./game/星际收集者/star_collector.py",
        "category": "冒险",
        "rating": 4.3,
        "play_count": 0,
        "last_played": None,
        "image": "assets/game_log/星际收集者/logo.png",
        "settings": {
            "difficulty": "easy",
            "sound": True,
            "controls": "keyboard"
        },
        "status": "available"
    },
    {
        "id": "lane_conflict",
        "name": "兵线冲突",
        "description": "策略类塔防游戏，管理兵线和资源对抗敌人",
        "path": "./game/兵线冲突/main.py",
        "category": "策略",
        "rating": 4.4,
        "play_count": 0,
        "last_played": None,
        "image": "",
        "settings": {
            "difficulty": "normal",
            "ai_level": "medium",
            "sound": True
        },
        "status": "available"
    },
    {
        "id": "sandbox_war",
        "name": "模拟沙盘战争",
        "description": "复杂的战争模拟策略游戏，包含建筑、单位、资源管理",
        "path": "./game/模拟沙盘战争/SimulateSandboxWarfare.py",
        "category": "策略",
        "rating": 4.1,
        "play_count": 0,
        "last_played": None,
        "image": "",
        "settings": {
            "map_size": "medium",
            "ai_difficulty": "normal",
            "resources": "standard",
            "auto_save": True
        },
        "status": "available"
    },
    {
        "id": "game_2048",
        "name": "2048",
        "description": "数字合并益智游戏，滑动数字达到2048目标",
        "path": "./game/2048/2048.py",
        "category": "益智",
        "rating": 4.0,
        "play_count": 0,
        "last_played": None,
        "image": "",
        "settings": {
            "board_size": "4x4",
            "animation": True,
            "sound": False,
            "auto_save": True
        },
        "status": "available"
    }
]

def load_games_config():
    """加载游戏配置"""
    if os.path.exists(CONFIG_FILE):
        try:
            with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        except:
            return DEFAULT_GAMES
    else:
        save_games_config(DEFAULT_GAMES)
        return DEFAULT_GAMES

def save_games_config(games_data):
    """保存游戏配置"""
    with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
        json.dump(games_data, f, ensure_ascii=False, indent=2)

@app.route('/')
def index():
    """提供HTML页面"""
    base_dir = get_base_dir()
    return send_from_directory(base_dir, 'game_center.html')

@app.route('/api/games', methods=['GET'])
def get_games():
    """获取所有游戏"""
    games = load_games_config()
    return jsonify(games)

@app.route('/api/games/<game_id>/start', methods=['POST'])
def start_game(game_id):
    """启动游戏"""
    games = load_games_config()
    game = next((g for g in games if g['id'] == game_id), None)
    
    if not game:
        return jsonify({'error': '游戏不存在'}), 404
    
    # 使用路径工具获取完整的游戏路径
    game_path = get_game_path(game['path'])
    
    # 检查文件是否存在
    if not os.path.exists(game_path):
        return jsonify({'error': f'游戏文件不存在: {game_path}'}), 404
    
    try:
        # 启动游戏
        if game_path.endswith('.py'):
            python_cmd = get_python_command()
            game_dir = os.path.dirname(game_path)
            subprocess.Popen([python_cmd, game_path], cwd=game_dir)
        else:
            subprocess.Popen([game_path], cwd=os.path.dirname(game_path))
        
        # 更新游戏统计
        game['play_count'] += 1
        game['last_played'] = datetime.now().isoformat()
        save_games_config(games)
        
        return jsonify({
            'success': True, 
            'message': f'游戏 "{game["name"]}" 已启动！',
            'play_count': game['play_count']
        })
        
    except Exception as e:
        return jsonify({'error': f'启动游戏失败: {str(e)}'}), 500

@app.route('/api/games/<game_id>/settings', methods=['PUT'])
def update_game_settings(game_id):
    """更新游戏设置"""
    games = load_games_config()
    game = next((g for g in games if g['id'] == game_id), None)
    
    if not game:
        return jsonify({'error': '游戏不存在'}), 404
    
    settings = request.json
    game['settings'].update(settings)
    save_games_config(games)
    
    return jsonify({'success': True, 'message': '设置已保存'})

@app.route('/api/games', methods=['POST'])
def add_game():
    """添加新游戏"""
    data = request.json
    games = load_games_config()
    
    # 生成唯一ID
    game_id = data['name'].lower().replace(' ', '_').replace('_', '')
    counter = 1
    while any(g['id'] == game_id for g in games):
        game_id = f"{data['name'].lower().replace(' ', '_')}_{counter}"
        counter += 1
    
    new_game = {
        "id": game_id,
        "name": data['name'],
        "description": data['description'],
        "path": data['path'],
        "category": data['category'],
        "rating": data.get('rating', 4.0),
        "play_count": 0,
        "last_played": None,
        "image": data.get('image', ''),
        "settings": {
            "difficulty": "normal",
            "sound": True
        },
        "status": "available"
    }
    
    games.append(new_game)
    save_games_config(games)
    
    return jsonify({'success': True, 'message': '游戏已添加', 'game': new_game})

@app.route('/api/stats', methods=['GET'])
def get_stats():
    """获取统计信息"""
    games = load_games_config()
    
    total_games = len(games)
    available_games = len([g for g in games if g['status'] == 'available'])
    total_plays = sum(g['play_count'] for g in games)
    most_played = max(games, key=lambda x: x['play_count'], default=None)
    
    return jsonify({
        'total_games': total_games,
        'available_games': available_games,
        'total_plays': total_plays,
        'most_played': most_played
    })

# 静态文件服务
@app.route('/assets/<path:filename>')
def serve_assets(filename):
    """提供静态资源文件"""
    assets_dir = os.path.join(get_base_dir(), 'assets')
    return send_from_directory(assets_dir, filename)

if __name__ == '__main__':
    print("🎮 游戏集合中心服务器启动中...")
    print("📝 访问 http://localhost:5000 打开游戏中心")
    print("⚡ 现在可以正常启动游戏了！")
    app.run(debug=True, host='0.0.0.0', port=5000) 